package com.collabscm.tools.ant;

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Filter;
import org.apache.tools.ant.types.FilterSet;
import org.apache.tools.ant.util.FileUtils;

/**
 * 仅将beginToken和endToken删除，保持内容不变。
 * @author Zeng Raoxing
 */
public class TrimFilter extends Filter {
	
	private File filtersFile;
	
    public void setFiltersfile(File filtersFile) {
    	log("call setFiltersFile.", Project.MSG_VERBOSE);
		this.filtersFile = filtersFile;
	}

	/**
     * Execute the task.
     * @throws BuildException on error
     */
    public void execute() throws BuildException {
        if (filtersFile == null) {
            throw new BuildException("filtersFile parameter is required", getLocation());
        }
        readFiltersFromFile(filtersFile);
    }
    
    public synchronized void readFiltersFromFile(File filtersFile) throws BuildException {
    	if (filtersFile.isFile()) {
            log("Reading filters from " + filtersFile, Project.MSG_VERBOSE);
            FileInputStream in = null;
            try {
               Properties props = new Properties();
               in = new FileInputStream(filtersFile);
               props.load(in);
               FilterSet set = getProject().getGlobalFilterSet();
               Enumeration<?> e = props.propertyNames();
               while (e.hasMoreElements()) {
                  String strPropName = (String) e.nextElement();
                  String value;
                  if(strPropName.startsWith("$")) {
                	  int second$ = strPropName.indexOf("$", 1);
                	  if(second$ > 0) {
                		  value = strPropName.substring(second$ + 1);
                	  } else {
                		  value = strPropName;
                	  }
                  } else {
                	  value = strPropName;
                  }
                  set.addFilter(new FilterSet.Filter(strPropName, value));
               }
            } catch (Exception ex) {
               throw new BuildException("Could not read filters from file: "
                   + filtersFile, ex);
            } finally {
               FileUtils.close(in);
            }
         } else {
        	 log("The filtersFile:" + filtersFile + " is not File." , Project.MSG_ERR);
        	 throw new BuildException("The filtersFile:" + filtersFile + " is not File.", getLocation());
         }
    }

}
